package com.security.springboot.dao;

import com.security.springboot.dto.PermissionDto;
import com.security.springboot.dto.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public UserDto getUserByUsername (String username) {
        List<UserDto> list = jdbcTemplate.query("select * from t_user where username = ?", new Object[] {username},
                new BeanPropertyRowMapper<>(UserDto.class));
        return list.size() > 0 ? list.get(0) : null;
    }

    public List<String> getUserRoles (String userId){
       String sql = "SELECT * FROM t_permission WHERE id IN (\n" +
               "SELECT permission_id FROM t_role_permission WHERE role_id IN (\n" +
               "  SELECT role_id FROM t_user_role WHERE user_id = "+userId+"\n" +
               "))";
       List<PermissionDto> list = jdbcTemplate.query(sql, new Object[] {},
               new BeanPropertyRowMapper<>(PermissionDto.class));
        List<String> permissionCodes = new ArrayList<>();
        list.forEach(c -> permissionCodes.add(c.getPermission_code()));
        return permissionCodes;
    }
}
